/**
 * 
 */
package com.ditty.invoke.handler;

import com.ditty.handler.AbstractHttpHandler;
import com.ditty.wrap.HttpRequestWrapper;
import com.ditty.wrap.HttpResponseWrapper;

/**
 * @author dingnate
 *
 */
public class HandlerInvoker implements IHandlerInvoker {
	private AbstractHttpHandler handler;
	private HttpRequestWrapper httpRequestWrapper;
	private HttpResponseWrapper httpResponseWrapper;
	private boolean handled;
	private String target;

	public HandlerInvoker(AbstractHttpHandler handler, HttpRequestWrapper httpRequestWrapper, HttpResponseWrapper httpResponseWrapper) {
		this.handler = handler;
		this.target = httpRequestWrapper.uri();
		this.httpRequestWrapper = httpRequestWrapper;
		this.httpResponseWrapper = httpResponseWrapper;

	}

	@Override
	public IHandlerInvoker handle() {
		if (handler != null) {
			AbstractHttpHandler pop = handler;
			handler = handler.next;
			pop.handle(this);
		} else if (!handled) {
			handled = true;
		}
		return this;
	}

	/**
	 * @return the httpRequestWrapper
	 */
	@Override
	public final HttpRequestWrapper getHttpRequestWrapper() {
		return httpRequestWrapper;
	}

	/**
	 * @return the httpResponseWrapper
	 */
	@Override
	public final HttpResponseWrapper getHttpResponseWrapper() {
		return httpResponseWrapper;
	}

	/**
	 * @return the target
	 */
	public final String getTarget() {
		return target;
	}

	/**
	 * @param target the target to set
	 */
	public final IHandlerInvoker setTarget(String target) {
		this.target = target;
		return this;
	}
}
